import { defineStore } from "pinia";

/*
* jsonp请求
*/
import { jsonp } from "vue-jsonp";

export const useMapStore = defineStore("map", {
  state: () => ({
    mapKey: "BWVBZ-H2TKK-2WJJO-AP63F-DTP52-JVFCK", // 腾讯地图key
    location: {}, // 位置信息
  }),
  actions: {
    /*
    * 获取位置及周边信息
    */
    setLocation(location) {
      return new Promise((resolve, reject) => {
        const { latitude, longitude } = location;
        this.location = location;
        const url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${this.mapKey}&get_poi=1`;
        jsonp(url, { output: "jsonp" })
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    /*
    * 搜索周边信息
    */
    setSearch(val) {
      console.log(this.location, "this.location");
      return new Promise((resolve, reject) => {
        const url = `https://apis.map.qq.com/ws/place/v1/search`;
        jsonp(url, { key: this.mapKey, keyword: val, boundary: `nearby(${this.location.latitude},${this.location.longitude},${1000},${1})`, output: 'jsonp' })
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
  },
});
